package calao.client.ui;

import calao.client.Country;
import calao.client.Desktop;
import calao.client.ServiceCallback;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.ListBox;

public class CountryBox
extends ListBox
implements HasDeferredLoading
{

	public final static String NULL_CODE = ""; 

	public CountryBox() 
	{
		// check if last loaded form has a country box
		Form form = Form.lastLoadedForm;
		CountryBox model = null;
		if (form!=null) {
			for (int i=0; i<form.fields.size(); i++) {
				Form.Field field = (Form.Field)form.fields.get(i);
				if (field.editor instanceof CountryBox) {
					//Desktop.getDesktop().log("Using country box model");
					model = (CountryBox)field.editor;
					break;
				}
			}
		}
		if (model!=null) {
			for (int i=0; i<model.getItemCount(); i++) {
				addItem(model.getItemText(i), model.getValue(i));
			}			
		}
		else {
			// otherwise load the list from the server...
			//Desktop.getDesktop().log("Fetching country list");
			Desktop.getDesktop().getSessionService().listCountries(new ServiceCallback() {
				protected void onReturn(Object result) {
					Country[] countries = (Country[])result;
					java.util.Arrays.sort(countries, Country.getComparator());
					addItem(NumberedListBox.NULL_TEXT, NULL_CODE);
					for (int i=0; i<countries.length; i++) {
						Country country = countries[i];
						addItem(country.getName(), country.getCode());
					}
				}
			});
		}
	}

	public void setSelectedCountry(final String code)
	{
		// defer to make sure items are properly loaded
		ServiceCallback.defer(new Command() {
			public void execute() {
				for (int i=0; i<getItemCount(); i++) {
					String value = getValue(i);
					setItemSelected(i, code==null? value.length()==0 : value.equals(code));
				}
			}
		});		
	}

	public String getSelectedCountry()
	{
		int index = getSelectedIndex();
		return index>0? getValue(index) : null;
	}

}
